package com.sgj.completable;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 异步调用
 * @Author: Guoji Shen
 * @Date: 2021/8/10 10:32
 */
public class CompletableFutuerDemo {

    private static final Integer SUCCESS = 200;
    private static final Integer ERROR = 500;

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 没有返回值的 runAsync 异步回调
        // runAsync();

        // 有返回值的 supplyAsync 异步回调
        supplyAsync();
    }

    public static void runAsync() throws ExecutionException, InterruptedException {
        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "runAsync->Void");
        });

        // 一定是先执行的
        System.out.println("111");
        // 获取执行结果
        completableFuture.get();
    }

    public static void supplyAsync() throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "supplyAsync->Integer");
            // 人为制造错误
            // int i = 10 / 0;
            return SUCCESS;
        });

        // 是否执行成功
        Integer integer = completableFuture.whenComplete((t, u) -> {
            // t输出正确返回值
            System.out.println("t->" + t);
            // u输出错误信息
            System.out.println("u->" + u);
        }).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return ERROR;
        }).get();
        System.out.println(integer);
    }
}